from django.db.models import QuerySet

from django.shortcuts import render, HttpResponse, redirect
from django.core.paginator import Paginator
from django.views.generic import DetailView

from article.models import Article
from comment.models import Comment


def index(request):
    all_article_list = Article.objects.all().order_by('created_time')
    paginator = Paginator(all_article_list, 10)  # 实例化分页器对象
    page = int(request.GET.get('page', 1))  # 获取页码数
    article_list_obj = paginator.page(page)  # 获取当前页的分页对象
    article_list = article_list_obj.object_list  # 获取当前页的数据列表
    context = {
        'article_list': article_list,
        'paginator': paginator,
        'article_list_obj': article_list_obj
    }
    return render(request, 'article/index.html', context=context)


def traverse_tree(current_comment, depth, nums: list):
    # print(current_comment, depth)

    nums.append(current_comment)

    # 查询子评论
    children: QuerySet = current_comment.replies.all()

    # 叶子节点
    if not children.exists(): return

    # 遍历子节点
    for i in children:
        traverse_tree(i, depth + 1, nums)


def article_detail(request, article_id):
    # 获取评论
    if request.method == 'GET':
        article = Article.objects.get(id=article_id)
        comment_list = Comment.objects.filter(article_id=article.id, parent=None).order_by('post_time')
        nums = []
        resultSet = []
        for i in comment_list:
            traverse_tree(i, 0, nums)
            resultSet.append(nums.copy())
            nums.clear()

        context = {
            'article': article,
            'request': request,
            'comments': resultSet
        }

        return render(request, 'article/article_detail.html', context=context)
    # 评论提交
    else:
        c_id = article_id
        c_author = request.user.id
        c_content = request.POST.get('content')
        Comment.objects.create(content=c_content, article_id=c_id, author_id=c_author)
        return redirect('/blog/article_detail/{}/'.format(c_id))


def my_test(request):
    return render(request, "article/comment_detail.html")


class ArticleDetailView(DetailView):
    model = Article
    template_name = 'page/article_detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = self.object.article_comments.filter(parent=None).order_by('-post_time')
        return context
